<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌号码" prop="licensePlate">
        <el-input
          v-model="queryParams.licensePlate"
          placeholder="请输入车牌号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车型" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入车型"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basicInformation:car:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['basicInformation:car:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basicInformation:car:remove']"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basicInformation:car:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键id" align="center" prop="id" v-if="false"/>
      <el-table-column label="使用状态" align="center" prop="lamp" width="180">
        <template slot-scope="scope">
          <el-tooltip placement="top" content="正常" effect="dark" v-if="scope.row.lamp === '1'">
            <img src="../../../../public/image/car/green-lamp.png"/>
          </el-tooltip>
          <el-tooltip placement="top" content="即将到期" effect="dark" v-if="scope.row.lamp === '2'">
            <img src="../../../../public/image/car/red-lamp.png"/>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="在线状态" align="center" prop="isOnline">
        <template slot-scope="scope">
          <el-tooltip placement="top" content="在线" effect="dark" v-if="scope.row.isOnline === true">
            <img src="../../../../public/image/car/green-lamp.png"/>
          </el-tooltip>
          <el-tooltip placement="top" content="离线" effect="dark" v-if="scope.row.isOnline === false">
            <img src="../../../../public/image/car/red-lamp.png"/>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="定位" align="center" prop="isOnline">
        <template slot-scope="scope">
          <el-button v-if="scope.row.isOnline !== null"
                     size="mini"
                     type="text"
                     @click="handleOpenMap(scope.row,1)"
          >定位
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="终端名称" align="center" prop="equipmentName"/>
      <el-table-column label="终端编号" align="center" prop="equipmentNumber"/>
      <el-table-column label="车牌号码" align="center" prop="licensePlate"/>
      <el-table-column label="车型" align="center" prop="model"/>
      <el-table-column label="发动机号码" align="center" prop="engineNumber"/>
      <el-table-column label="底盘号码" align="center" prop="chassisNumber"/>
      <el-table-column label="责任人" align="center" prop="cadre"/>
      <el-table-column label="联系方式" align="center" prop="contact"/>
      <el-table-column label="车类型" align="center" prop="type"/>
      <el-table-column label="使用年限" align="center" prop="serviceLife"/>
      <el-table-column label="所属部门" align="center" prop="deptName"/>
<!--      <el-table-column label="使用截止日期" align="center" prop="useDeadline" width="180">
      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basicInformation:car:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basicInformation:car:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车辆信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="车牌号码" prop="licensePlate">
              <el-input v-model="form.licensePlate" placeholder="请输入车牌号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车型" prop="model">
              <el-input v-model="form.model" placeholder="请输入车型"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发动机号码" prop="engineNumber">
              <el-input v-model="form.engineNumber" placeholder="请输入发动机号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="底盘号码" prop="chassisNumber">
              <el-input v-model="form.chassisNumber" placeholder="请输入底盘号码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="责任人" prop="cadre">
              <el-input v-model="form.cadre" placeholder="请输入责任人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系方式"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车类型" prop="type">
              <el-input v-model="form.type" placeholder="请输入车类型"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用年限" prop="serviceLife">
              <el-input v-model="form.serviceLife" placeholder="请输入使用年限"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="终端设备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用截止日期" prop="useDeadline">
              <el-date-picker clearable size="small"
                              v-model="form.useDeadline"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择使用截止日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="终端设备编码" prop="equipmentNumber">
              <el-input v-model="form.equipmentNumber" readonly style="width:223px"/>
              <el-button type="primary" v-model="form.terminalId" @click="selectTerminal">选择终端设备</el-button>
              <el-button type="primary" @click="unBundling" v-show="form.terminalId !== undefined">解绑
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="titleTerminal" :visible.sync="openTerminal" width="800px" append-to-body>
      <el-form :model="queryTerminalParams" ref="queryTerminalForm" :inline="true" v-show="showSearchTerminal"
               label-width="68px">
        <el-form-item label="设备名称" prop="equipmentName">
          <el-input
            v-model="queryTerminalParams.equipmentName"
            placeholder="请输入设备名称"
            clearable
            size="small"
            @keyup.enter.native="handleQueryTerminal"
          />
        </el-form-item>
        <el-form-item label="设备编号" prop="equipmentNumber">
          <el-input
            v-model="queryTerminalParams.equipmentNumber"
            placeholder="请输入设备编号"
            clearable
            size="small"
            @keyup.enter.native="handleQueryTerminal"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryTerminal">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetTerminalQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="terminalList" @selection-change="handleSelectionChangeTerminal">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="主建id" align="center" prop="id" v-if="false"/>
        <el-table-column label="设备名称" align="center" prop="equipmentName"/>
        <el-table-column label="设备编号" align="center" prop="equipmentNumber"/>
      </el-table>
      <pagination
        v-show="totalTerminal>0"
        :total="totalTerminal"
        :page.sync="queryTerminalParams.pageNum"
        :limit.sync="queryTerminalParams.pageSize"
        @pagination="getTerminalList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="okTerminal">确 定</el-button>
        <el-button @click="cancelTerminal">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="'地图'"
               :fullscreen="true"
               :visible="openMap"
               :close-on-click-modal="false"
               class="dialog_collect"
               @open="handleOpenDialog"
               @close="handleCloseDialog">
      <section class="dialog_body">
        <common-map
          ref="map"
          style="height: calc(100vh - 110px)"
          @map-click="ShowDetail"
          :isTool="false"
          :toolbarSelectVisible="false"
        >
        </common-map>
      </section>
      <car-detail
        :visible='showCarDialog'
        @close="showDetailDialog = -1"
        :width="600"
        ref="carDetail">
      </car-detail>
    </el-dialog>
  </div>
</template>

<script>
  import {unBundling, listCar, getCar, delCar, addCar, updateCar, exportCar} from '@/api/basicInformation/car'
  import {listTerminal} from '@/api/basicInformation/terminal'
  import carDetail from '@/views/onemap/Detail/carDetail'

  export default {
    name: 'Car',
    components: {
      carDetail
    },
    computed: {
      showCarDialog() {
        return this.showDetailDialog === 0
      }
    },
    data() {
      return {
        map: null,
        showDetailDialog: -1,
        openMap: false,
        rowData: {},
        marker: [],
        idsTerminal: [],
        terminalNames: [],
        terminalNumbers: [],
        // 显示搜索条件
        showSearchTerminal: true,
        totalTerminal: 0,
        terminalList: [],
        titleTerminal: '选择终端设备',
        openTerminal: false,
        queryTerminalParams: {
          pageNum: 1,
          pageSize: 10,
          equipmentName: undefined,
          equipmentNumber: undefined,
          terminalType: '2',
          isBinding: '1'
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        names: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 车辆信息管理表格数据
        carList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          licensePlate: undefined,
          model: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          equipmentNumber: [
            {required: true, message: '请绑定终端', trigger: 'change'}
          ],
          licensePlate: [
            {required: true, message: "车牌号码不能为空", trigger: "blur"},
            {min: 0, max: 30, message: '长度在 0 到 30 个字符', trigger: 'blur'}
          ],
          useDeadline: [
            {required: true, message: "使用截止日期不能为空", trigger: "blur"}
          ],
          engineNumber: [
            {required: true, message: "发动机号码不能为空", trigger: "blur"},
            {min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: 'blur'}
          ],
          contact: [
            {required: true, message: "联系方式不能为空", trigger: "blur"},
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确格式的联系方式",
              trigger: "blur"
            }
          ]
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getTerminalList() {
        this.loading = true
        listTerminal(this.queryTerminalParams).then(response => {
          this.terminalList = response.rows
          this.totalTerminal = response.total
          this.loading = false
        })
      },
      okTerminal() {
        if (this.idsTerminal.length > 1) {
          this.msgInfo('只能绑定一个终端设备')
        } else if (this.idsTerminal.length === 1) {
          this.form.terminalId = this.idsTerminal[0]
          this.form.equipmentName = this.terminalNames[0]
          this.form.equipmentNumber = this.terminalNumbers[0]
          this.openTerminal = false
        } else {
          this.msgInfo('请选择终端设备')
        }
      },
      cancelTerminal() {
        this.openTerminal = false
      },
      handleQueryTerminal() {
        this.queryTerminalParams.pageNum = 1
        this.getTerminalList()
      },
      resetTerminalQuery() {
        this.resetForm('queryTerminalForm')
        this.handleQueryTerminal()
      },
      // 多选框选中数据
      handleSelectionChangeTerminal(selection) {
        this.idsTerminal = selection.map(item => item.id)
        this.terminalNames = selection.map(item => item.equipmentName)
        this.terminalNumbers = selection.map(item => item.equipmentNumber)
      },
      selectTerminal() {
        this.openTerminal = true
        this.handleQueryTerminal()
      },
      /** 查询车辆信息管理列表 */
      getList() {
        this.loading = true
        listCar(this.queryParams).then(response => {
          this.carList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          lamp: undefined,
          licensePlate: undefined,
          model: undefined,
          engineNumber: undefined,
          chassisNumber: undefined,
          cadre: undefined,
          contact: undefined,
          type: undefined,
          serviceLife: undefined,
          terminalId: undefined,
          terminalIdOld: undefined,
          equipmentNumber: undefined,
          equipmentName: undefined,
          useDeadline: undefined,
          delFlag: undefined,
          createById: undefined,
          createBy: undefined,
          createTime: undefined,
          updateById: undefined,
          updateBy: undefined,
          updateTime: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.names = selection.map(item => item.licensePlate)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加车辆信息管理'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids
        getCar(id).then(response => {
          this.form = response.data
          this.form.terminalIdOld = this.form.terminalId
          this.open = true
          this.title = '修改车辆信息管理'
        })
      },
      unBundling() {
        let that = this
        this.$confirm('是否确认解绑终端设备', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return unBundling({terminalId: that.form.terminalId})
        }).then(() => {
          this.msgSuccess('解绑成功')
          this.open = false
          this.getList()
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          const PlateNumMatch = /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/
          if (this.form.licensePlate != null && !PlateNumMatch.test(this.form.licensePlate)) {
            this.msgError('车牌号错误')
          } else {
            if (valid) {
              if (this.form.id != null) {
                updateCar(this.form).then(response => {
                  this.msgSuccess('修改成功')
                  this.open = false
                  this.getList()
                })
              } else {
                addCar(this.form).then(response => {
                  this.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                })
              }
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        const names = row.licensePlate || this.names
        this.$confirm('是否确认删除车牌号为"' + names + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delCar(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$confirm('是否确认导出所有车辆信息管理数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return exportCar(queryParams)
        }).then(response => {
          this.download(response.msg)
        })
      },
      handleOpenMap(row, e) {
        this.openMap = true
        this.rowData = row
      },
      handleOpenDialog() {
        this.$nextTick(() => {
          this.map = this.$refs.map.map
          this.marker.push({
            coordinates: [this.rowData.x, this.rowData.y],
            id: this.rowData.id,
            title: this.rowData.licensePlate,
            target: 'car',
            animate: true,
            stopEvent: true,
            iconUrl: '/image/map/car.png',
            item: this.rowData
          })
          this.$refs.map.showMarkerFeature(this.marker, false, 'car')
          this.$refs.map.map.getMap().getView().animate({
            center: [this.rowData.x, this.rowData.y],
            duration: 500
          })
        })
      },
      ShowDetail(e) {
        this.$refs.carDetail.handleShowCaseInfo(e, this.map)
        this.showDetailDialog = 0
      },
      handleCloseDialog() {
        this.showDetailDialog = -1
        this.marker = []
        this.openMap = false
        this.$forceUpdate()
      }
    }
  }
</script>
